package com.liyue.application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Environment;

import com.liyue.xupdate.XUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author liyue
 * @date 2021/6/10
 * <p>
 * 错误日志收集    存储路径  /ERROR/@{time}
 */
public class BaseApplication extends Application {

    protected static Context mContext = null;
    protected static Activity mActivity = null;
    //记录崩溃信息
    final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();

    @Override
    public void onCreate() {
        super.onCreate();
        XUtil.init( getApplicationContext());
        mContext = getApplicationContext();
        //TODO:收集崩溃日志
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                //获取崩溃时的UNIX时间戳
                long timeMillis = System.currentTimeMillis();
                //将时间戳转换成人类能看懂的格式，建立一个String拼接器
                StringBuilder stringBuilder = new StringBuilder(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(timeMillis)));
                stringBuilder.append(":\n");
                //获取错误信息
                stringBuilder.append(throwable.getMessage());
                stringBuilder.append("\n");
                //获取堆栈信息
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                stringBuilder.append(sw.toString());

                //这就是完整的错误信息了，你可以拿来上传服务器，或者做成本地文件保存等等等等
                String errorLog = stringBuilder.toString();
                try {
                    Date date = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                    String filePath = getSaveDirectory() + File.separator + "ERROR" + File.separator + formatter.format(date);
                    String fileName = System.currentTimeMillis() + ".text";
                    File file = new File(filePath + File.separator + fileName);
                    newFolder(getSaveDirectory() + File.separator + "ERROR", formatter.format(date));
                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    BufferedWriter out = new BufferedWriter(new FileWriter(file));
                    out.write(errorLog);
                    out.close();
                } catch (IOException e) {
                }
                //最后如何处理这个崩溃，这里使用默认的处理方式让APP停止运行
                defaultHandler.uncaughtException(thread, throwable);
            }
        });
    }

    public String getSaveDirectory() {

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            return Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            return null;
        }
    }

    /*新建文件夹方法,参数为新建文件夹所存放的路径和名称.如果新建成功返回true;否则,返回false;*/
    public static Boolean newFolder(String path, String name) {
        File file = new File(path, name);
        if (!file.exists()) {
            if (file.isFile()) {
                return false;
            } else {
                file.mkdirs();
                return true;
            }
        } else {
            return false;
        }
    }


    public static Context getmContext() {

            return mContext;

    }

    public static void setmActivity(Activity activity) {
        mActivity = activity;
    }

    public static Activity getmActivity() {
        return mActivity;
    }
}
